package com.kk.admin.controller;

import com.kk.admin.param.AdminUserParam;
import com.kk.admin.pojo.AdminUser;
import com.kk.admin.service.AdminUserService;
import com.kk.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * projectName: b2c-store
 *
 * @author: kjy
 * time: 2023/5/12 17:54
 * description: 后台管理用户处理的controller
 */
@RestController
public class AdminUserController {

    @Autowired
    private AdminUserService adminUserService;

    //前端传的数据不是json，不用加@RequestBody
    @PostMapping("/user/login")
    public R login(@Validated AdminUserParam adminUserParam, BindingResult result, HttpSession session){

        //参数校验
        if (result.hasErrors()){
            return R.fail("核心参数为null，登录失败!");
        }

        //验证码校验
        String captcha = (String) session.getAttribute("captcha");
//        System.out.println("captcha"+captcha);

        //session清空后，captcha.equals(?)会报空指针异常。
        if (!adminUserParam.getVerCode().equalsIgnoreCase(captcha)){
            return R.fail("验证码错误！");
        }

        AdminUser user = adminUserService.login(adminUserParam);

        if (user == null){
            return R.fail("登录失败！账号或密码错误！");
        }

        session.setAttribute("userInfo",user);

        return R.ok("登录成功！");
    }

    @GetMapping("user/logout")
    public R logout(HttpSession session){
        //清空session
        session.invalidate();//session的所有数据清空
        return R.ok("退出登录成功！");
    }

}
